package com.example.redissonlock.controller;

import lombok.extern.slf4j.Slf4j;
import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@RestController
@Slf4j
public class RedissonLockController {

    @RequestMapping("redissonLock")
    public String redissonLock(){
        Config config = new Config();
        config.useSingleServer().setAddress("redis://101.37.247.31:6379");
//        config.useClusterServers().addNodeAddress("redis://101.37.247.31:6379",
//                                                    "redis://110.40.180.241:6379",
//                                                    "redis://121.196.42.169:6379");
        config.useSingleServer().setPassword("log131415926");
        RedissonClient redisson = Redisson.create(config);
        RLock rLock = redisson.getLock("order");
        log.info("我进入了方法！");
        try {
            // leaseTIme: 获取后持有锁的最长时间，获取分布式锁
            // 该方法会等待 直到获取到锁
            rLock.lock(30, TimeUnit.SECONDS);
            log.info("我获得了锁！！！");
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            log.info("我释放了锁！！");
            rLock.unlock();
        }
        log.info("方法执行完成！");
        return "方法执行完成！";
    }

    @Autowired
    private RedissonClient redisson;
    /**
     * 使用Spring于Redisson整合的jar包
     * 使用 自动注册的RedissonClient
     * @return
     */
    @RequestMapping("redissonLock1")
    public String redissonLock1(){

        RLock rLock = redisson.getLock("order");
        log.info("我进入了方法！");
        try {
            // leaseTIme: 获取后持有锁的最长时间，获取分布式锁
            // 该方法会等待 直到获取到锁
            rLock.lock(30, TimeUnit.SECONDS);
            log.info("我获得了锁！！！");
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            log.info("我释放了锁！！");
            rLock.unlock();
        }
        log.info("方法执行完成！");
        return "方法执行完成！";
    }
}
